<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>文件上传 - 维修故障排查系统</title>
</head>
<body>
    <div layout:fragment="content">
        <div class="row">
            <div class="col-12">
                <h1 class="mb-4">文件上传管理</h1>
            </div>
        </div>

        <div class="row">
            <!-- 坐标文件上传 -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-table me-2"></i>坐标文件上传
                        </h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">支持格式：*.csv, *.xy, *.txt</p>
                        <p class="small text-muted">格式要求：Designator,X,Y,Layer</p>
                        
                        <div class="upload-area" id="coordinate-upload-area">
                            <div class="text-center p-4 border rounded">
                                <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                <p class="mb-3">拖拽文件到此处或</p>
                                <button class="btn btn-primary" onclick="document.getElementById('coordinate-file').click()">
                                    选择文件
                                </button>
                                <input type="file" id="coordinate-file" class="d-none" 
                                       accept=".csv,.xy,.txt" onchange="uploadCoordinateFile()">
                            </div>
                        </div>
                        
                        <div id="coordinate-preview" class="mt-3" style="display: none;">
                            <h6>坐标预览</h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>元件</th>
                                            <th>X坐标</th>
                                            <th>Y坐标</th>
                                            <th>层</th>
                                        </tr>
                                    </thead>
                                    <tbody id="coordinate-table-body"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 位置图上传 -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-image me-2"></i>位置图上传
                        </h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">支持格式：*.jpg, *.png</p>
                        <p class="small text-muted">支持任意分辨率</p>
                        
                        <div class="upload-area" id="image-upload-area">
                            <div class="text-center p-4 border rounded">
                                <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                <p class="mb-3">拖拽图片到此处或</p>
                                <button class="btn btn-primary" onclick="document.getElementById('image-file').click()">
                                    选择图片
                                </button>
                                <input type="file" id="image-file" class="d-none" 
                                       accept=".jpg,.jpeg,.png" onchange="uploadImageFile()">
                            </div>
                        </div>
                        
                        <div id="image-preview" class="mt-3" style="display: none;">
                            <h6>图片预览</h6>
                            <img id="preview-image" class="img-fluid rounded" style="max-height: 200px;">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 原理图上传 -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-file-pdf me-2"></i>原理图上传
                        </h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">支持格式：*.pdf</p>
                        <p class="small text-muted">支持矢量图和扫描图</p>
                        
                        <div class="upload-area" id="pdf-upload-area">
                            <div class="text-center p-4 border rounded">
                                <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                <p class="mb-3">拖拽PDF到此处或</p>
                                <button class="btn btn-primary" onclick="document.getElementById('pdf-file').click()">
                                    选择文件
                                </button>
                                <input type="file" id="pdf-file" class="d-none" 
                                       accept=".pdf" onchange="uploadPdfFile()">
                            </div>
                        </div>
                        
                        <div id="pdf-preview" class="mt-3" style="display: none;">
                            <h6>PDF信息</h6>
                            <div id="pdf-info" class="small"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 上传历史 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">上传历史</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>文件名</th>
                                        <th>类型</th>
                                        <th>大小</th>
                                        <th>上传时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="upload-history">
                                    <tr>
                                        <td colspan="5" class="text-center text-muted">暂无上传记录</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div layout:fragment="scripts">
        <script>
            // 拖拽上传支持
            ['coordinate-upload-area', 'image-upload-area', 'pdf-upload-area'].forEach(areaId => {
                const area = document.getElementById(areaId);
                if (area) {
                    area.addEventListener('dragover', (e) => {
                        e.preventDefault();
                        area.classList.add('border-primary');
                    });
                    
                    area.addEventListener('dragleave', () => {
                        area.classList.remove('border-primary');
                    });
                    
                    area.addEventListener('drop', (e) => {
                        e.preventDefault();
                        area.classList.remove('border-primary');
                        
                        const files = e.dataTransfer.files;
                        if (files.length > 0) {
                            const file = files[0];
                            if (areaId === 'coordinate-upload-area') {
                                handleCoordinateFile(file);
                            } else if (areaId === 'image-upload-area') {
                                handleImageFile(file);
                            } else if (areaId === 'pdf-upload-area') {
                                handlePdfFile(file);
                            }
                        }
                    });
                }
            });

            function uploadCoordinateFile() {
                const fileInput = document.getElementById('coordinate-file');
                if (fileInput.files.length > 0) {
                    handleCoordinateFile(fileInput.files[0]);
                }
            }

            function uploadImageFile() {
                const fileInput = document.getElementById('image-file');
                if (fileInput.files.length > 0) {
                    handleImageFile(fileInput.files[0]);
                }
            }

            function uploadPdfFile() {
                const fileInput = document.getElementById('pdf-file');
                if (fileInput.files.length > 0) {
                    handlePdfFile(fileInput.files[0]);
                }
            }

            function handleCoordinateFile(file) {
                const formData = new FormData();
                formData.append('file', file);

                fetch('/upload/coordinates', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('坐标文件上传成功', 'success');
                        displayCoordinatePreview(data.coordinates);
                        addToHistory(file.name, '坐标文件', file.size);
                    } else {
                        showToast(data.error || '上传失败', 'error');
                    }
                })
                .catch(error => {
                    showToast('上传失败: ' + error.message, 'error');
                });
            }

            function handleImageFile(file) {
                const formData = new FormData();
                formData.append('file', file);

                fetch('/upload/image', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('图片上传成功', 'success');
                        displayImagePreview(data.url);
                        addToHistory(file.name, '位置图', file.size);
                    } else {
                        showToast(data.error || '上传失败', 'error');
                    }
                })
                .catch(error => {
                    showToast('上传失败: ' + error.message, 'error');
                });
            }

            function handlePdfFile(file) {
                const formData = new FormData();
                formData.append('file', file);

                fetch('/upload/pdf', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('PDF上传成功', 'success');
                        displayPdfPreview(file.name, file.size);
                        addToHistory(file.name, '原理图', file.size);
                    } else {
                        showToast(data.error || '上传失败', 'error');
                    }
                })
                .catch(error => {
                    showToast('上传失败: ' + error.message, 'error');
                });
            }

            function displayCoordinatePreview(coordinates) {
                const preview = document.getElementById('coordinate-preview');
                const tableBody = document.getElementById('coordinate-table-body');
                
                tableBody.innerHTML = '';
                coordinates.slice(0, 5).forEach(coord => {
                    const row = tableBody.insertRow();
                    row.innerHTML = `
                        <td>${coord.designator}</td>
                        <td>${coord.x.toFixed(2)}</td>
                        <td>${coord.y.toFixed(2)}</td>
                        <td>${coord.layer}</td>
                    `;
                });
                
                if (coordinates.length > 5) {
                    const row = tableBody.insertRow();
                    row.innerHTML = `<td colspan="4" class="text-center text-muted">... 共${coordinates.length}条记录</td>`;
                }
                
                preview.style.display = 'block';
            }

            function displayImagePreview(imageUrl) {
                const preview = document.getElementById('image-preview');
                const img = document.getElementById('preview-image');
                img.src = imageUrl;
                preview.style.display = 'block';
            }

            function displayPdfPreview(filename, fileSize) {
                const preview = document.getElementById('pdf-preview');
                const info = document.getElementById('pdf-info');
                info.innerHTML = `
                    <p><strong>文件名:</strong> ${filename}</p>
                    <p><strong>大小:</strong> ${formatFileSize(fileSize)}</p>
                `;
                preview.style.display = 'block';
            }

            function addToHistory(filename, type, size) {
                const history = document.getElementById('upload-history');
                if (history.querySelector('td[colspan="5"]')) {
                    history.innerHTML = '';
                }
                
                const row = history.insertRow();
                row.innerHTML = `
                    <td>${filename}</td>
                    <td><span class="badge bg-primary">${type}</span></td>
                    <td>${formatFileSize(size)}</td>
                    <td>${new Date().toLocaleString()}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-danger" onclick="removeFromHistory(this)">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;
            }

            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            function removeFromHistory(button) {
                const row = button.closest('tr');
                row.remove();
                
                const history = document.getElementById('upload-history');
                if (history.rows.length === 0) {
                    history.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无上传记录</td></tr>';
                }
            }

            function showToast(message, type) {
                const toast = document.createElement('div');
                toast.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
                toast.style.top = '20px';
                toast.style.right = '20px';
                toast.style.zIndex = '9999';
                toast.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.body.appendChild(toast);
                
                setTimeout(() => toast.remove(), 3000);
            }
        </script>
    </div>
</body>
</html>
